package com.yu8home.mq.rabbit.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        System.out.println("交换机 发布确认 及 回退 的初始化");
    }

    // 消息发送到 Broker 后触发回调，确认消息是否到达 Broker 服务器，也就是只确认是否正确到达 Exchange 中
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData == null ? "" : correlationData.getId();
        log.info("交换机发布确认信息：correlationData={} ,ack={}, cause={}", id, ack, cause);
    }

    // 启动消息失败返回，比如路由不到队列时触发回调
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("消息传递异常回退：{}", returnedMessage.toString());
    }

}
